from rest_framework.viewsets import ModelViewSet

from apps.meiduo_admin.serializers.admin_user import UserSerializer
from apps.users.models import User
from apps.meiduo_admin.utils.pagination import MeiduoPagination
from django.views import View
import json
from django.http import JsonResponse
import datetime
import jwt
from django.conf import settings

#管理员管理  增删改查操作
class UserViewSet(ModelViewSet):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = UserSerializer
    pagination_class = MeiduoPagination


class LoginView(View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get("password")
        #验证
        if not all([username,password]):
            return JsonResponse({'msg':'数据不完整'},status=400)
        try:
            user = User.objects.get(username= username,is_staff=True)
        except:
            return JsonResponse({'msg':'用户名不对'},status=400)
        if not user.check_password(password):
            return JsonResponse({'msg':'密码无效'},status=400)
        #生成token
        payload = {
            'id':user.id,
            'username':user.username,
            'exp':datetime.datetime.utcnow() + datetime.timedelta(days=14)
        }
        token = jwt.encode(payload,settings.SECRET_KEY).decode()

        #响应
        return JsonResponse({
            'user_id':user.id,
            'username':user.username,
            'token':token
        })
